<!-- 模板 -->
<template>
  <div class="params-root">
    <!-- 1、导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/login' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>参数管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <!-- 2、警告条 -->
      <el-alert title="只能对三级分类进行操作" type="warning" show-icon :closable="false"></el-alert>
      <!-- 3、商品分类的级联选择器 -->
      <el-row>
        <el-col>
          <span>请选择商品分类:</span>
          <el-cascader v-model="value" :options="cateList" :props="prop" @change="handleChange" clearable></el-cascader>
        </el-col>
      </el-row>
      <!-- 4、动态/静态参数标签页 -->
      <el-tabs v-model="activeName" @tab-click="handleTabClick">
        <el-tab-pane label="动态参数" name="many">
          <!-- 添加分类参数button -->
          <el-button type="primary" size="mini" :disabled="!getId" @click="showManyDialog">添加动态参数</el-button>
          <!-- 动态分类参数table -->
          <el-table :data="manyTable" border style="width: 100%" :header-cell-style="headerCellStyle">
            <el-table-column type="expand" label="展开" width="100" align="center">
              <template v-slot="scope">
                <el-tag
                  v-for="(item, index) in scope.row.attr_vals"
                  :key="index"
                  closable
                  @close="updateParams(scope.row, item)"
                >
                  {{ item }}
                </el-tag>
                <!-- 动态编辑标签 -->
                <el-input
                  class="input-new-tag"
                  v-show="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="savetaginput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                ></el-input>
                <el-button
                  v-show="!scope.row.inputVisible"
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                >
                  +new tag
                </el-button>
              </template>
            </el-table-column>
            <el-table-column type="index" label="序号" width="100" align="center"></el-table-column>
            <el-table-column prop="attr_name" label="参数名称" width="280"></el-table-column>
            <el-table-column label="操作" align="center">
              <template v-slot="scope">
                <el-button type="primary" icon="el-icon-edit" size="mini" @click="showUpdateManyDialog(scope.row)"
                  >修改</el-button
                >
                <el-button type="danger" icon="el-icon-delete" size="mini" @click="deleteParamsById(scope.row)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="静态参数" name="only">静态参数</el-tab-pane>
      </el-tabs>
    </el-card>
    <!-- 5、添加动态参数的对话框 -->
    <el-dialog title="添加动态参数" :visible.sync="addManyDialogVisible" width="50%" @close="handleAddManyClose">
      <el-form
        :model="addManyForm"
        :rules="addManyFormRules"
        ref="addManyFormRef"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="参数名称" prop="attr_name">
          <el-input class="many-input" v-model="addManyForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addManyDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addManyParams()">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 6、修改动态参数的对话框 -->
    <el-dialog title="修改动态参数" :visible.sync="updateManyDialogVisible" width="50%" @close="handleUpdateManyClose">
      <el-form
        :model="updateManyForm"
        :rules="addManyFormRules"
        ref="updateManyFormRef"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="参数名称" prop="attr_name">
          <el-input class="many-input" v-model="updateManyForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="updateManyDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="updateManyParams()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import request from '@/utils/request.js'
export default {
  name: '',
  data() {
    return {
      //12、修改动态参数的对话框绑定的数据源
      updateManyForm: {
        attr_name: ''
      },
      //11、控制修改动态参数的对话框是否显示
      updateManyDialogVisible: false,
      //10、添加动态参数表单验证规则
      addManyFormRules: {
        attr_name: [
          { required: true, message: '请输入参数名称', trigger: 'blur' },
          { min: 2, max: 15, message: '长度在 2 到 15 个字符', trigger: 'blur' }
        ]
      },
      //9、添加动态参数表单的数据源
      addManyForm: {
        attr_name: ''
      },
      //8、控制添加动态参数对话框是否显示
      addManyDialogVisible: false,
      //7、表头的样式
      headerCellStyle: {
        backgroundColor: '#409EFF',
        color: '#ffffff',
        textAlign: 'center'
      },
      //6、动态参数列表
      manyTable: [],
      //5、静态参数列表
      onlyTable: [],
      //4、标签页激活的标记
      activeName: 'many',
      //3、级联选择器的选择的配置项
      prop: {
        expandTrigger: 'hover',
        value: 'cat_id',
        label: 'cat_name',
        children: 'children'
      },
      //2、级联选择器的选择的数据
      value: [],
      //1、商品分类列表
      cateList: []
    }
  },
  computed: {
    //获得级联选择器的选择的id数组最后一个元素 [1,3,6]
    getId() {
      if (!this.value || this.value.length === 0) {
        return 0
      }
      return this.value[2]
    }
  },
  methods: {
    //15、根据参数的id删除动态参数
    async deleteParamsById(row) {
      let flag = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(e => e)
      if (flag !== 'confirm') {
        return this.message.info('你取消了删除')
      }
      let id = this.getId
      let attrid = row.attr_id
      let options = {
        url: `categories/${id}/attributes/${attrid}`,
        type: 'delete'
      }
      let { data: res } = await request(options)
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.$message.success('删除成功！')
      this.getTable()
    },
    //14、修改动态参数
    updateManyParams() {
      this.$refs['updateManyFormRef'].validate(async valid => {
        if (!valid) {
          return this.$message.error('请正确填写参数名称')
        }
        let id = this.getId
        let attrId = this.updateManyForm.attr_id
        let attr_name = this.updateManyForm.attr_name
        let attr_sel = this.activeName
        //参数要传递，否则会全部删除原有的参数属性值，后台只接收字符串
        let attr_vals = this.updateManyForm.attr_vals.join(',')
        let options = {
          url: `categories/${id}/attributes/${attrId}`,
          type: 'put',
          data: { attr_name, attr_sel, attr_vals }
        }
        let { data: res } = await request(options)
        if (res.meta.status !== 200) {
          return this.$message.error(res.meta.msg)
        }
        this.$message.success('修改参数成功')
        this.updateManyDialogVisible = false
        this.getTable()
      })
    },
    //13、修改动态参数对话框隐藏触发的函数
    handleUpdateManyClose() {
      this.$refs['updateManyFormRef'].resetFields()
    },
    //12、显示修改动态参数对话框
    showUpdateManyDialog(row) {
      //合并对象row属性到this.updateManyForm中
      Object.assign(this.updateManyForm, row)
      this.updateManyDialogVisible = true
    },
    //11、点击显示添加动态参数对话框
    showManyDialog() {
      this.addManyDialogVisible = true
    },
    //10、添加动态参数
    addManyParams() {
      this.$refs['addManyFormRef'].validate(async valid => {
        if (!valid) {
          return this.$message.error('请填写正确名称')
        }
        let id = this.getId
        let attr_sel = this.activeName
        let attr_name = this.addManyForm.attr_name
        let options = {
          url: `categories/${id}/attributes`,
          type: 'post',
          data: { attr_sel, attr_name }
        }
        let { data: res } = await request(options)
        if (res.meta.status !== 201) {
          return this.$message.error(res.meta.msg)
        }
        this.$message.success('添加动态参数成功')
        this.getTable()
        this.addManyDialogVisible = false
      })
    },
    //9、添加对话框隐藏时触发的函数
    handleAddManyClose() {
      this.$refs['addManyFormRef'].resetFields()
    },
    //8、点击显示input隐藏button,同时input获得焦点
    showInput(row) {
      row.inputVisible = true
      //input框显示时就获得焦点
      this.$nextTick(function() {
        //获得焦点
        this.$refs.savetaginput.$refs.input.focus()
      })
    },
    //7、动态添加参数的属性
    handleInputConfirm(row) {
      row.inputVisible = false
      //1、获得当前input的值
      let value = row.inputValue
      if (value.trim().length === 0) {
        return
      }
      //2、添加value到attr_vals数组中
      row.attr_vals.push(value)
      //3、提交修改当前参数的请求
      this.saveParams(row)
      row.inputValue = ''
    },
    //6、保存修改后的参数对象
    async saveParams(row) {
      let attr_vals = row.attr_vals
      let options = {
        url: `categories/${this.getId}/attributes/${row.attr_id}`,
        type: 'put',
        data: {
          attr_name: row.attr_name,
          attr_sel: this.activeName,
          attr_vals: attr_vals.join(',')
        }
      }
      //提交请求
      let { data: res } = await request(options)
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.$message.success('修改成功')
    },
    //5、修改参数的属性值
    async updateParams(row, value) {
      //修改参数的属性值
      let attr_vals = row.attr_vals
      let index = attr_vals.findIndex(item => item === value)
      attr_vals.splice(index, 1)
      //准备参数
      this.saveParams(row)
    },
    //4、获得指定id的参数列表
    async getTable() {
      //重置表格数据
      this.manyTable = []
      this.onlyTable = []
      //通过计算属性获得id值
      let id = this.getId
      //如果没有选择商品分类，则不请求数据
      if (!id) {
        return this.$message.error('请选在商品分类')
      }
      //准备参数
      let options = {
        url: `categories/${id}/attributes`,
        type: 'get',
        data: { sel: this.activeName }
      }
      let { data: res } = await request(options)
      //保存数据
      //这是修改的数据
      if (this.activeName === 'many') {
        res.data.forEach(item => {
          let str = item.attr_vals.split(',')
          item.attr_vals = str.filter(i => i !== '')
          //控制input是否显示
          item.inputVisible = false
          //绑定input值
          item.inputValue = ''
        })
        this.manyTable = res.data
      } else {
        this.onlyTable = res.data
      }
    },
    //3、点击标签页触发的操作
    handleTabClick(tab) {
      this.activeName = tab.name
      this.getTable()
    },
    //2、级联选择器发生变化时的操作
    handleChange() {
      this.getTable()
    },
    //1、获得商品分类信息
    async getCateList() {
      let options = {
        url: 'categories',
        type: 'get'
      }
      let { data: res } = await request(options)
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.cateList = res.data
    }
  },
  created() {
    this.getCateList()
  },
  mounted() {}
}
</script>

<style lang="less" scoped>
//@import url(); 引入公共css类
.el-row {
  margin: 0.15rem 0;
}
.el-tag {
  margin: 0.1rem;
}
.el-cascader {
  margin-left: 0.1rem;
}
.el-input {
  width: 1rem;
}
.button-new-tag {
  width: 1rem;
}
.many-input {
  width: 100%;
}
</style>
